package com.baiqian.doupo.capability.douqi;

import com.baiqian.doupo.capability.DouPoModCapability;
import com.baiqian.doupo.network.Networking;
import com.baiqian.doupo.network.SendPack;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class DouQiCapabilityProvider implements ICapabilityProvider, INBTSerializable<CompoundNBT> {
    private IDouQiCapability douQiCapability;
    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        return cap == DouPoModCapability.DOUQI_CAPABILTTY ? LazyOptional.of(this::getOrCreateCapability).cast() : LazyOptional.empty();
    }

    @Nonnull
    IDouQiCapability getOrCreateCapability() {//初始化玩家能力
        if (douQiCapability == null) {//如果没有能力
            this.douQiCapability = new DouQiPlayerCapability();
            if(Minecraft.getInstance().player!=null){//向服务端请求数据
                Networking.INSTANCE.sendToServer(new SendPack(1));
            }
        }
        return this.douQiCapability;
    }

    @Override
    public CompoundNBT serializeNBT() {
        return getOrCreateCapability().serializeNBT();
    }

    @Override
    public void deserializeNBT(CompoundNBT nbt) {
        getOrCreateCapability().deserializeNBT(nbt);
    }

}
